import {
	hostUrl
} from "@/config/index.js"

import {
	navigateToLogin
} from '@/assets/scripts/navigate.js'

const getToken = () => {
	const token = uni.getStorageSync('token')

	if (token) {
		return token
	} else {
		navigateToLogin()
		return
	}
}

const upload = async (table, field, tempFilePath, config = {}) => {
	return new Promise((resolve, rejuct) => {
		uni.uploadFile({
			url: hostUrl + '/oss/upload?table=' + table + '&field=' + field,
			filePath: tempFilePath,
			name: 'file',
			formData: {},
			...config,
			header: config.header ? {} : {
				Authorization: "Bearer " + getToken()
			},
			success: (uploadRes) => {
				if (uploadRes.statusCode === 200) {
					resolve(JSON.parse(uploadRes.data))
				} else {
					navigateToLogin()
					rejuct()
				}
			},
			fail: (error) => {
				navigateToLogin()
				rejuct()
			}
		});
	})


}

const request = async (method, url, data = {}, config = {}) => {
	return new Promise((resolve, rejuct) => {
		uni.request({
			method,
			url: hostUrl + url,
			data,
			...config,
			header: config.header ? {} : {
				Authorization: "Bearer " + getToken()
			},
			success: (res) => {
				if (res.statusCode === 200) {
					resolve(res.data)
				} else {
					navigateToLogin()
					rejuct()
				}
			},
			fail: () => {
				navigateToLogin()
				rejuct()
			}
		})
	})
}

export {
	request,
	upload,
}